import fg from "fast-glob";
import fs from "fs-extra";
import path from "path";
import { UnityHelper } from "./UnityHelper.js";
import { toolchain } from "../toolchain.js";
import { Relatives } from "./Relatives.js";
import { HardCodeCollector } from "./HardCodeCollector.js";
import { ProjectHelper } from "./ProjectHelper.js";
import { standardPath } from "./vendor.js";

export class ImageStriper {
    public async removeUseless(r: Relatives): Promise<void> {
        const outFile = `tmp/${toolchain.opts.projectName}.imageStriper.txt`;
        await fs.ensureFile(outFile);
        await fs.writeFile(outFile, '', 'utf-8');

        const keepMap: { [file: string]: string } = {};
        const usedByCfgMap: { [icon: string]: string } = {};

        // 收集配置中配了的图标
        //#region 
        await ProjectHelper.readKeepCfg(keepMap, usedByCfgMap);
        // 收集ts代码/cs代码引用到的ui prefab
        //#region 
        await HardCodeCollector.ensureData();
        //#endregion

        // 收集用到的guid
        //#region 
        const usedGUIDMap = await UnityHelper.collectUsedGUID(toolchain.opts.projectRoot);
        //#endregion

        // 收集图片
        //#region 
        let cnt = 0;
        const imgRoots = ['Assets/AssetSources', 'Assets/Arts'];
        for (const ir of imgRoots) {
            const imgs = await fg(['**/*.png', '**/*.jpg', '**/*.tga'], { cwd: path.join(toolchain.opts.projectRoot, ir), ignore: ['font/**/@*/*.*', 'channel/**/*.*', 'icon/**/*.*', 'images/atlas/actBtnIcon/*.*', 'map/**/*.*', 'platIcon/**/*.*'] });
            for (const img of imgs) {
                if (img.includes('@')) continue;
                // if (!img.includes('yh_')) {
                //     continue;
                // }
                const f = path.join(ir, img);
                const file = path.join(toolchain.opts.projectRoot, f);
                const metaFile = file + '.meta';
                const guid = await UnityHelper.readGUID(metaFile);
                if (!usedGUIDMap[guid]) {
                    // 未被直接引用
                    if (!r.isUsed || r.isRelated(guid)) {
                        const imglc = img.toLowerCase();
                        if (keepMap[f]) {
                            await fs.appendFile(outFile, `[KEEP] ${img}    by keep rule: ${keepMap[f]}\n`, 'utf-8');
                        } else if (usedByCfgMap[imglc]) {
                            await fs.appendFile(outFile, `[KEEP] ${img}    by cfg rule: ${usedByCfgMap[imglc]}\n`, 'utf-8');
                        } else {
                            const hu = HardCodeCollector.isUsed(img);
                            if (hu) {
                                await fs.appendFile(outFile, `[CODE] ${img}    by hard code: ${hu}\n`, 'utf-8');
                            } else {                                
                                // 未被代码引用
                                await r.collect(file);
                                await fs.unlink(file);
                                await fs.unlink(metaFile);
                                cnt++; 
                            }                           
                        }
                    }
                }
            }
        }

        //#endregion

        console.log('deleted images cnt:', cnt);
        console.log(`部分未被直接使用的图片因KEEP规则或代码中引用而保留，详见: ${outFile}`);
    }
}
